Repository navigation
fix(consumer): keep an in-flight message instead of dropping it as a duplicate - #7
Open
muhammetsafak wants to merge 4 commits into
Open
muhammetsafak wants to merge 4 commits into
muhammetsafak wants to merge 4 commits into
Conversation
…duplicate With idempotency enabled, a redelivery that found its key claimed by an unfinished handler was acknowledged and discarded. If that handler's worker had died the message was lost, and if the handler outlived the transport's redelivery time and then threw, the discarded duplicate had already deleted the PDO row, so the retry updated nothing. Add CompletionAwareIdempotencyStore (extends IdempotencyStore, adds isCompleted()). When the store implements it, the Dispatcher drops a completed duplicate but releases an in-flight one without counting an attempt, delayed by the new IdempotencyOptions::$inFlightDelaySeconds. Outcome::release() gains an optional delay, which the Worker passes to the transport and follows with a short pause so transports without native delay do not spin. Stores that implement only IdempotencyStore keep the old behaviour. Correct the forget() and contract docblocks and rewrite the idempotent consumption docs.
Putting a message back to wait for another handler's in-flight key ran through transport steps that could lose or fork it. - AmqpTransport: publish the new copy (waiting for the broker confirm when the channel is in confirm mode) before acking the original, for both release() and deadLetter(). A crash in between leaves a duplicate the dispatcher recognises instead of nothing, and a failed publish leaves the original unacked. nack(requeue) was rejected: it would put the waiting message back at the head and block the queue behind it. - RedisTransport: release(), deadLetter() and the delayed-set migration are Lua scripts, atomic, and act only when the worker's LREM removed its own processing entry, so a worker whose message a reaper already reclaimed no longer forks it into two copies. - PdoTransport: release() updates only a row still held with the reservation stamp it wrote, and a message put back unchanged no longer rewrites payload or attempts. - Worker: a deferral is not counted towards maxJobs or processedCount(), and pauses at least 0.1s even with sleepWhenEmpty 0. Docs: the PDO store recipe resets completed on takeover, rolling-upgrade notes, the reaper requirements on Redis, drain and maxJobs behaviour, and the API reference for the idempotency types. Tests cover AMQP and Redis with fixtures and against real brokers in the integration job.
…trust a nack A failure reported by a worker that no longer holds its message was dropped on PDO and Redis, so a handler slower than the reservation or the reaper never reached maxAttempts, and the consume path started to need EVAL. RabbitMQ in confirm mode acked the original after a broker nack. - PdoTransport: a retry from a worker whose reservation was taken over records attempts, payload and back-off without touching the holder's reservation. attempts never moves back and an unchanged release never shortens a back-off. - RedisTransport: a worker that lost its processing entry replaces the live copy (delayed set, then queue) instead of being ignored, for release and dead-letter, so attempts climb and maxAttempts ends the message without forking it. A client that cannot EVAL falls back to the same steps as separate commands; reserve, ack and publish never need scripting. - AmqpTransport: a broker nack or returned copy requeues the original with basic_nack and throws QueueException instead of acking. The caller's own nack handler and return listener are wrapped and put back. Docs state the guarantees of the scripted and command-by-command Redis paths separately, the confirm-mode behaviour, and the PDO release rules.
When RabbitMQ nacked a republish, the original was requeued and the worker took it straight back, re-running its handler in a tight loop without counting an attempt or applying a back-off. The worker now pauses after a process failure: the larger of 0.1s, sleepWhenEmpty and the back-off for the message's next attempt, capped at 5s and taken in short slices that a stop signal ends at once. Attempts cannot advance while the broker refuses the new copy; the RabbitMQ docs state that limit and advise a separate channel for a handler's own publishes. The Redis fallback now treats only NOPERM and unknown command as "scripting unavailable".
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
With idempotency enabled, a redelivery whose key was claimed by a handler that had not finished was acknowledged and discarded as a
duplicate. Two ways to lose the message followed:Changes
Contracts\CompletionAwareIdempotencyStore(extendsIdempotencyStore) withisCompleted(string $key): bool.InMemoryIdempotencyStoreimplements it.Dispatcher: when a claim fails and the store is completion-aware, a completed key is dropped as before; an in-flight key is released (job.released, reasonin_flight) without counting an attempt, so waiting never walks a message to the dead-letter queue.IdempotencyOptions::$inFlightDelaySeconds(optional last argument, default 5, must be >= 1) paces the re-check.Outcome::release()gets an optional$delaySeconds; theWorkerpasses it to the transport and pausessleepWhenEmptyafter a delayed release so RabbitMQ (no native delay) does not spin.forget()is called by the dispatcher; the contract listsforget()).Idempotent-Consumption, README, Troubleshooting, Transport-PDO, FAQ, The-Worker, API-Reference, Core-Concepts, Retries) andCHANGELOG.md[Unreleased].Compatibility (minor, 2.3.0)
IdempotencyStoreand its signatures are unchanged. A custom store that implements onlyIdempotencyStorekeeps the previous behaviour (any failed claim is dropped). Records written by 2.1/2.2 should be read as completed byisCompleted(); the upgrade notes are indocs/Idempotent-Consumption.md.Not covered
A worker that finishes the handler and dies before
remember()still runs the handler twice after the lease lapses, and a handler that outlives its lease can run concurrently. Both are documented. A claim that never lapses (leaseSeconds: 0) keeps its message waiting untilforget().Verification
composer validate --strict,php-cs-fixer fix --dry-run --diff,phpstan analyse,phpunit(118 tests) pass locally.InFlightRedeliveryTestfails 7 of 10 tests when the dispatcher is made to drop in-flight keys again (both loss paths, on a real SQLitePdoTransporttoo).PdoTransport, shared lease-aware store, workers killed with SIGKILL) shows S1 and S4 endingLOSTbefore and with the row kept (jobs=1, released) after.wiki-sync.sh --check docsexits 0.Update: transport fixes (review round 1)
The in-flight wait itself could lose or fork a message on some transports, so
src/Transport/**is in scope:release()/deadLetter()publish the new copy (waiting for the confirm when the channel is in confirm mode) before acking the original. A crash in between leaves a duplicate the dispatcher recognises, not a gap; a failed publish leaves the original unacked.basic_nack(requeue)was rejected because it puts the waiting message back at the head and blocks the queue behind it.release(),deadLetter()and the delayed-set migration are Lua scripts and act only when the worker'sLREMremoved its own processing entry, so a reaped message is not forked into two copies.release()is conditional on the reservation stamp, and a message put back unchanged no longer rewritespayload/attempts.maxJobs/processedCount()and pauses at least 0.1 s.completedon takeover, rolling-upgrade notes (drain first), Redis reaper requirements, drain/maxJobsbehaviour, API reference. Redis and RabbitMQ integration tests added (run in the existing Integration job; also run locally against redis:7 and rabbitmq:3.13).Update: review round 2
attempts/payload/back-off without touching the holder's reservation; Redis replaces the live copy (delayed set, then queue) instead of ignoring the call. A handler slower thanretryAfteror the reaper still reachesmaxAttemptsand the dead-letter list, with idempotency on or off.EVALis optional. A client without it (an adapter limited to the documented commands, or no scripting permission) falls back to the same steps as separate commands; the docs state each path's guarantees.nackor returned copy requeues the original and throws instead of acking; the caller's own handlers keep running. Verified against a real broker with areject-publishqueue.